import { login, logout, getAuthRule } from "@/api/login";
import {
  getToken,
  setToken,
  removeToken,
  setName,
  removeName,
  setMerchantId,
  removeMerchantId,
  setAccount,
  removeAccount,
  setPhoto,
  removePhoto,
} from "@/utils/auth";
import { resetRouter } from "@/router";
import router from "@/router";

const state = {
  token: getToken(),
  menu: [],
  rule: [],
  ruleIds: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_MENU: (state, menu) => {
    state.menu = menu;
  },
  SET_RULE: (state, rule) => {
    state.rule = rule;
  },
  SET_RULEIDS: (state, ruleIds) => {
    state.ruleIds = ruleIds;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      const name = username.trim();
      login({ mobile: name, password: password })
        .then((response) => {
          let data = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          setName(data.shopname);
          setMerchantId(data.merchantId);
          setAccount(name);
          setPhoto(data.photo);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 获取用户授权菜单
  getMenu({ commit, state }) {
    return new Promise((resolve, reject) => {
      getAuthRule()
        .then((response) => {
          if (!response) {
            reject("授权失败，请重新登录！");
          }
          const { menu, rule, ruleIds } = response;
          // 如果没有页面级，则整个菜单隐藏
          let filterList = [];
          for (let item of menu) {
            if (item.children) {
              let obj = { ...item };
              obj.children = [];
              for (let child of item.children) {
                if (child.children) {
                  obj.children.push(child);
                }
              }
              if (obj.children.length > 0) {
                filterList.push(obj);
              }
            }
          }
          commit("SET_MENU", filterList);
          commit("SET_RULE", rule);
          commit("SET_RULEIDS", ruleIds);
          resolve({ menu: filterList });
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_MENU", []);
          commit("SET_RULE", []);
          commit("SET_RULEIDS", []);
          removeToken();
          removeName();
          removeMerchantId();
          removeAccount();
          removePhoto();
          resetRouter();
          router.push("/login");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_MENU", []);
      commit("SET_RULE", []);
      commit("SET_RULEIDS", []);

      removeToken();
      removeName();
      removeMerchantId();
      removeAccount();
      removePhoto();
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
